package com.dongdongshop.mq;

import com.dongdongshop.constant.RedisSeckill;
import com.dongdongshop.pojo.seckill.TbSeckillGoods;
import com.dongdongshop.pojo.seckill.TbSeckillOrder;
import com.dongdongshop.util.IdWorker;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Component
@RocketMQMessageListener(topic = "SECKILLGOODS",consumerGroup = "seckill-group")
public class MQSeckillGoodsConsumer implements RocketMQListener<Map> {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IdWorker idWorker;


    @Override
    public void onMessage(Map map) {
        Long seckillId = Long.parseLong(map.get("seckillId").toString());
        Long userId = Long.parseLong(map.get("userId").toString());

        TbSeckillGoods  seckillGoods = (TbSeckillGoods)redisTemplate.boundHashOps(RedisSeckill.KEY).get(RedisSeckill.FILED+seckillId);
        //保存订单
        TbSeckillOrder seckillOrder = new TbSeckillOrder();
        long orderId = idWorker.nextId();
        seckillOrder.setId(orderId);
        seckillOrder.setCreateTime(new Date());
        seckillOrder.setMoney(seckillGoods.getCostPrice());//秒杀价
        seckillOrder.setSeckillId(seckillId);
        seckillOrder.setSellerId(seckillGoods.getSellerId());
        seckillOrder.setStatus("0");
        seckillOrder.setUserId(userId+"");
        redisTemplate.boundHashOps(RedisSeckill.KEYORDER).put(userId+"_"+seckillId,seckillOrder);//限制用户交易

    }
}
